'use strict';

const Service = require('egg').Service;

class HousesService extends Service {
  commonAttr(app) {
    return {
      order: [[ 'showCount', 'DESC' ]],
      attributes: {
        exclude: [ 'startTime', 'endTime', 'publishTime' ],
      },
      include: [
        {
          model: app.model.Imgs,
          limit: 1,
          attributes: [ 'url' ],
        },
      ],
    };
  }

  async getHots() {
    const { ctx, app } = this;
    const result = await ctx.model.Houses.findAll({
      ...this.commonAttr(app),
      limit: 4,
    });

    return result;
  }

  async searchHouses(params) {
    const { ctx, app } = this;
    const { lte, gte, like } = app.Sequelize.Op;
    const where = {
      cityCode: Array.isArray(params.code) ? params.code[0] : params.code,
      startTime: {
        [gte]: params.startTime,
      },
      endTime: {
        [lte]: params.endTime,
      },
      name: {
        [like]: '%' + params.houseName + '%',
      },
    };
    if (!params.houseName) {
      delete where.name;
    }
    const result = await ctx.model.Houses.findAll({
      ...this.commonAttr(app),
      limit: Number(params.pageSize),
      offset: (params.pageNum - 1) * params.pageSize,
      where,
    });

    return result;
  }

  async houseDetail(id) {
    const { ctx, app } = this;
    const result = await ctx.model.Houses.findOne({
      where: {
        id,
      },
      include: [
        {
          model: app.model.Imgs,
          attributes: [ 'url' ],
        },
      ],
    });

    await ctx.model.Houses.update(
      {
        showCount: result.showCount + 1,
      },
      {
        where: {
          id,
        },
      }
    );
    return result;
  }
}

module.exports = HousesService;
